package pers.whj.rpc.server;

import pers.whj.rpc.common.Config;
import pers.whj.rpc.common.ReflectionUtils;
import pers.whj.rpc.protocol.Request;
import pers.whj.rpc.protocol.ServiceDescriptor;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务管理类，负责注册服务，查找服务
 */
public class ServiceManager {
    private static volatile ServiceManager instance;
    private final Map<ServiceDescriptor, ServiceInstance> services;

    public static ServiceManager getInstance() {
        if (instance == null) {
            synchronized (ServiceManager.class) {
                if (instance == null) {
                    instance = new ServiceManager();
                }
            }
        }
        return instance;
    }

    private ServiceManager() {
        this.services = new ConcurrentHashMap<>();
    }

    /**
     * 注册服务
     *
     * @param clazz 类对象
     * @param bean  类实例
     * @param <T>   实例类型
     */
    public <T> void register(Class<T> clazz, T bean) {
        Method[] methods = ReflectionUtils.getPublicMethods(clazz);
        for (Method method : methods) {
            ServiceInstance serviceInstance = new ServiceInstance(bean, method);
            ServiceDescriptor descriptor = ServiceDescriptor.from(clazz, method);
            this.services.put(descriptor, serviceInstance);
            if (Config.DEBUG) {
                System.out.println("成功注册服务: " + descriptor);
            }
        }
    }

    /**
     * 注销某个服务
     *
     * @param descriptor 服务描述
     * @return 是否存在并注销成功
     */
    public boolean unregister(ServiceDescriptor descriptor) {
        return this.services.remove(descriptor) != null;
    }

    /**
     * 根据请求对象查找服务
     *
     * @param request 请求
     * @return 若存在，返回服务实例，否则返回null
     */
    public ServiceInstance lookup(Request request) {
        ServiceDescriptor descriptor = request.getDescriptor();
        return this.services.get(descriptor);
    }
}
